package sa4.templating

import java.net.URLDecoder
import scala.xml._
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import scala.xml.transform._
import scala.xml.Null
import com.twitter.util.Eval

import java.io.{ StringWriter, PrintWriter }

import javax.script.ScriptException;

import scala.tools.nsc.InterpreterResults._
import scala.tools.nsc.{ Interpreter => ScalaInterpreter, Settings }

object parseTemplate {

  var path = "";
  var template = Seq();

  def parse(nameFileHtml: String): Seq[Node] = {
    var path = System.getProperty("user.dir") + "/html/"
    var result: Seq[Node] = null
    ProcessSurround(path)

    try {
      result = ProcessSurround.transform(xml.XML.loadFile(path + nameFileHtml))
    } catch {
      case noSuchFile: java.io.FileNotFoundException => result = ProcessSurround.transform(xml.XML.loadFile(path + "defaultError.html"))
    }

    //resp.getWriter().write(new PrettyPrinter(72, 2).formatNodes(result))
    return result
  }
  
  
  def parse(codeHtml:Elem) :Seq[Node] = {
    
    return  ProcessSurround.transform(codeHtml)
    
    
  }
  
}

class ProcessWrapper(ns: Seq[Node]) extends RewriteRule {

  override def transform(n: Node): Seq[Node] = n.label match {
    case "content" => ns
    case _ => n
  }
}

class ProcessScala(ns: Seq[Node]) extends RewriteRule {

  override def transform(n: Node): Seq[Node] = n match {

    case elem: Elem if elem.label == "scala" =>
      val code = elem.text
      val value = (new com.twitter.util.Eval).apply[Any](code)
      value match {
        case ns: NodeSeq => ns
        case s => <span> { s }</span>
      }
    case _ => n
  }
}

object ProcessSurround extends RewriteRule {

  var path = ""

  // val value = (new com.twitter.util.Eval).apply[Any](code)

  def apply(path: String) {
    this.path = path
  }

  override def transform(n: Node): Seq[Node] = n match {
    
    case elem: Elem if elem.label == "surround" =>
    var path = System.getProperty("user.dir") + "/html/"
      val wrapperName = (elem \\ "@with").text
      val wrapperNode = xml.XML.loadFile(path + wrapperName.toString())
      val wrappedNode = elem.child
      wrapperNode.map(ns => new RuleTransformer(new ProcessWrapper(wrappedNode), new ProcessScala(wrappedNode))(ns))

    case n => n
  }
}

